package com.example.basefream.controller;

import com.alibaba.fastjson.JSON;
import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.ctrip.framework.apollo.openapi.dto.NamespaceGrayDelReleaseDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenReleaseDTO;
import com.example.basefream.config.DevConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ：Mr-L
 * @date ：Created in 2022/4/13 12:12
 * @description：open api测试接口
 * @modified By：
 * @version: $
 */
@RestController
@RequestMapping("/openApi")
public class ApolloOpenController {

    @Autowired
    private DevConfig appConfig;

    @Autowired
    private ApolloOpenApiClient client;

    private String appId = "apolostTest";

    @GetMapping("/demo")
    public String hello() {
        return appConfig.getName();
    }

    //新增配置
    @PostMapping("/add")
    public Object addParam() {
        OpenItemDTO openItemDTO = new OpenItemDTO();
        openItemDTO.setKey("timeout");
        openItemDTO.setValue("100");
        openItemDTO.setComment("超时时间");
        openItemDTO.setDataChangeCreatedBy("apollo");
        OpenItemDTO item = client.createItem(appId, "DEV", "default", "Tong.CityConfig", openItemDTO);
        return JSON.toJSONString(item);
    }

    //修改配置
    @PostMapping("/update")
    public Object updateParam() {
        OpenItemDTO openItemDTO = new OpenItemDTO();
        openItemDTO.setKey("timeout");
        openItemDTO.setValue("200");
        openItemDTO.setComment("超时时间");
        openItemDTO.setDataChangeCreatedBy("apollo");
        client.createOrUpdateItem(appId, "DEV", "default", "Tong.CityConfig", openItemDTO);
        return JSON.toJSONString(openItemDTO);
    }

    //发布配置
    @PostMapping("/release")
    public Object releaseParam() {
        NamespaceGrayDelReleaseDTO namespaceGrayDelReleaseDTO = new NamespaceGrayDelReleaseDTO();
        namespaceGrayDelReleaseDTO.setReleaseTitle("2019-03-27 17:38 release");
        namespaceGrayDelReleaseDTO.setReleaseComment("test release");
        namespaceGrayDelReleaseDTO.setReleasedBy("apollo");
        OpenReleaseDTO openReleaseDTO = client.publishNamespace(appId, "DEV", "default", "Tong.CityConfig", namespaceGrayDelReleaseDTO);
        return JSON.toJSONString(openReleaseDTO);
    }

    //获取名称空间下所有的配置
    @GetMapping("/namespace")
    public Object getAllNameSpace() {
        return JSON.toJSONString(client.getNamespace(appId, "DEV", "default", "Tong.CityConfig"));
    }
}
